package cn.com.huzo.service.tech.impl;

import cn.com.huzo.model.entities.master.MaterialEntity;
import cn.com.huzo.model.entities.tech.CostForecastHeaderEntity;
import cn.com.huzo.model.entities.tech.CostForecastLinesEntity;
import cn.com.huzo.repository.master.MaterialRepository;
import cn.com.huzo.repository.tech.CostForecastLinesRepository;
import cn.com.huzo.repository.tech.CostForecastHeaderRepository;
import cn.com.huzo.service.tech.CostForecastLinesManager;
import huzofw.service.impl.GenericManagerImpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 产品成本预测表表明细管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("CostForecastLinesManager")
public class CostForecastLinesManagerImpl extends GenericManagerImpl<CostForecastLinesEntity, String>
        implements CostForecastLinesManager {

    @Resource(name = "CostForecastHeaderRepository")
    private CostForecastHeaderRepository _dao_header;

    @Resource(name = "CostForecastLinesRepository")
    private CostForecastLinesRepository _dao_lines;

    @Resource(name = "MaterialRepository")
    private MaterialRepository _dao_material;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    public List<CostForecastLinesEntity> fetchLinesByHeaderKey(Long headerId) throws Exception {
        return _dao_lines.fetchByHeaderKey(headerId);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<CostForecastLinesEntity> insertLinesByNewMaterial(List<CostForecastLinesEntity> itemList) throws Exception {
        // step1：插入数据
        Integer rowsAffected = _dao_lines.insertLinesByNewMaterial(itemList);
        // step2：重设顺序号
        _dao_lines.resetLinesOrder(itemList.get(0).getHeaderId());
        // step3：审计日志
        if (rowsAffected > 0) {
            // 更新相关主记录的最后操作时间，便于排序
            _dao_header.updateLastUpdatedDate(itemList.get(0).getHeaderId());
            // 记录日志
            CostForecastHeaderEntity _header = _dao_header.fetchByKey(itemList.get(0).getHeaderId(), null, null);
            writeAuditLog(itemList.get(0).getUpdatedBy(), "技术管理→成本预测明细",
                    "款号：" + _header.getStyleNo(),
                    "增加明细");
        }

        // 返回插入后的数据
        return _dao_lines.fetchByHeaderKey(itemList.get(0).getHeaderId());
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> batchUpdate(List<CostForecastLinesEntity> itemList) throws Exception {
        Map<String, Object> _result = new HashMap();
        List<Short> _err_rowno = new ArrayList();

        // 每个行都要判断料号，如果有错误就把行号保存到_err_rowno
        for (int i = 0; i < itemList.size(); i++) {
            if (_dao_lines.updateLinesByMaterialId(itemList.get(i).getLinesId(), itemList.get(i).getMaterialId()) <= 0) {
                // 如果没有料号的改变，则不做错误记录，否则记录下当前的行号
                if (itemList.get(i).getMaterialCode() != null) {
                    _err_rowno.add(itemList.get(i).getOrderNo());
                }
            }
        }

        // 如果料号没有错误，更新数据，否则就返回错误的行号
        if (_err_rowno.isEmpty()) {
            Integer rowsAffected = _dao_lines.batchUpdate(itemList);

            if (rowsAffected > 0) {
                // 更新相关主记录的最后操作时间，便于排序
                _dao_header.updateLastUpdatedDate(itemList.get(0).getHeaderId());
                // 记录日志
                CostForecastHeaderEntity _header = _dao_header.fetchByKey(itemList.get(0).getHeaderId(), null, null);
                writeAuditLog(itemList.get(0).getUpdatedBy(), "技术管理→成本预测明细",
                        "款号：" + _header.getStyleNo(),
                        "更新明细");
            }

            _result.put("Success", true);
            _result.put("LinesList", _dao_lines.fetchByHeaderKey(itemList.get(0).getHeaderId()));
        } else {
            _result.put("Success", false);
            _result.put("ErrRowNo", _err_rowno);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> updateLinesByMaterialId(Long headerId, String linesId, Long materialId, Long updatedBy) throws Exception {
        Map<String, Object> _result = new HashMap();
        if (_dao_lines.updateLinesByMaterialId(linesId, materialId) > 0) {
            // 更新相关主记录的最后操作时间，便于排序
            _dao_header.updateLastUpdatedDate(headerId);

            // 记录日志
            CostForecastHeaderEntity _header = _dao_header.fetchByKey(headerId, null, null);
            writeAuditLog(updatedBy, "技术管理→成本预测明细",
                    "款号：" + _header.getStyleNo() + "　料号：" + materialId,
                    "更新明细材料");

            MaterialEntity entity = _dao_material.fetchByMaterialId(materialId);
            _result.put("Success", true);
            _result.put("MaterialId", entity.getMaterialId());
            _result.put("MaterialName", entity.getMaterialName());
            _result.put("MaterialCode", entity.getMaterialCode());
            _result.put("Specification", entity.getSpecification());
            _result.put("SupplierName", entity.getSupplierName());
            _result.put("UomId", entity.getUomId());
            _result.put("UomName", entity.getUomName());
        } else {
            _result.put("Success", false);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> delete(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        // step1：删除
        Integer rowsAffected = _dao_lines.delete(MapUtils.getString(criterion, "LinesId"));
        if (rowsAffected > 0) {
            // step2：重设行号
            _dao_lines.resetLinesOrder(MapUtils.getLong(criterion, "HeaderId"));
            // 更新相关主记录的最后操作时间，便于排序
            _dao_header.updateLastUpdatedDate(MapUtils.getLong(criterion, "HeaderId"));
            // step3：审计日志
            writeAuditLog(MapUtils.getLong(criterion, "DeletedBy"),
                    "技术管理→成本预测明细",
                    "明细数据（" + MapUtils.getString(criterion, "LinesData") + "）",
                    "删除明细");
        }
        _result.put("LinesList", _dao_lines.fetchByHeaderKey(MapUtils.getLong(criterion, "HeaderId")));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<CostForecastLinesEntity> batchDeleteLines(List<CostForecastLinesEntity> itemList) throws Exception {
        // step1：删除
        Integer rowsAffected = _dao_lines.batchDelete(itemList);
        // step2：重设行号
        _dao_lines.resetLinesOrder(itemList.get(0).getHeaderId());
        // step3：审计日志
        if (rowsAffected > 0) {
            // 更新相关主记录的最后操作时间，便于排序
            _dao_header.updateLastUpdatedDate(itemList.get(0).getHeaderId());
            // 记录日志
            CostForecastHeaderEntity _header = _dao_header.fetchByKey(itemList.get(0).getHeaderId(), null, null);
            writeAuditLog(itemList.get(0).getDeletedBy(), "技术管理→成本预测明细",
                    "款号：" + _header.getStyleNo(),
                    "批量删除明细");
        }

        return _dao_lines.fetchByHeaderKey(itemList.get(0).getHeaderId());
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<CostForecastLinesEntity> insertFromClipboard(Long headerId, String copiedLinesId, Long materialId,
            Long uomId, String specification, Integer orderNo, Long createdBy, Long updatedBy) throws Exception {
        // 粘贴数据
        _dao_lines.insertFromClipboard(headerId, copiedLinesId, materialId,
                uomId, specification, orderNo, createdBy, updatedBy);
        // 重设顺序号
        _dao_lines.resetLinesOrder(headerId);

        // 更新相关主记录的最后操作时间，便于排序
        _dao_header.updateLastUpdatedDate(headerId);

        // 返回插入后的数据
        return _dao_lines.fetchByHeaderKey(headerId);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> importLinesFromOtherCostForecast(Long headerId, Long importedHeaderId,
            Long createdBy, Long updatedBy) throws Exception {
        Map<String, Object> _result = new HashMap();
        // 插入数据
        Integer rowsAffected = _dao_lines.importLinesFromOtherCostForecast(headerId, importedHeaderId, createdBy, updatedBy);
        if (rowsAffected > 0) {
            // 重设顺序号
            _dao_lines.resetLinesOrder(headerId);
            // 更新相关主记录的最后操作时间，便于排序
            _dao_header.updateLastUpdatedDate(headerId);
            // 记录日志
            CostForecastHeaderEntity _header = _dao_header.fetchByKey(headerId, null, null);
            writeAuditLog(updatedBy, "技术管理→成本预测明细",
                    "款号：" + _header.getStyleNo(),
                    "引入成本预测");
        }

        // 返回插入后的全部数据
        _result.put("LinesList", _dao_lines.fetchByHeaderKey(headerId));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> updateLinesOrder(List<CostForecastLinesEntity> itemList) throws Exception {
        Map<String, Object> _result = new HashMap();
        Integer rowsAffected = _dao_lines.updateLinesOrder(itemList);
        if (rowsAffected > 0) {
            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }
        _result.put("LinesList", _dao_lines.fetchByHeaderKey(itemList.get(0).getHeaderId()));

        return _result;
    }
}
